Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

367
Views
How to sum/group 2d array by multiple "columns/criteria" using reduce() in Javascript?

I've been dancing around with this, but can't figure out how to add a column or criteria. This groups by the first "column", but how to make it group also by the last column?

This is the answer:

let array = [[3, 'name', 'old'],[4, 'lastname','young'],[2, 'name', 'old'],[4, 'lastname','old']];

let result = Object.values(array.reduce((c, v) => {
  if (c[v[1]]) c[v[1]][0] += v[0];     //Add the first element if already exist
  else c[v[1]] = v;                    //Assign the value if does not exist
  return c;
}, {}));

console.log(result);

Expected Result

result = 
[
 [5, 'name', 'old'],
 [4, 'lastname','young'],
 [4, 'lastname','old']
];

Thank you!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In your situation, as a simple modification, for example, how about using the values of columns "B" and "C" as a key of the object of reduce as follows?

Modified script:

let array = [[3, 'name', 'old'], [4, 'lastname', 'young'], [2, 'name', 'old'], [4, 'lastname', 'old']];

let result = Object.values(array.reduce((c, v) => {
  const k = v[1] + v[2];
  if (c[k]) c[k][0] += v[0];
  else c[k] = v;
  return c;
}, {}));

console.log(result);

  • When this script is run, the following result is obtained.

      [
        [ 5, 'name', 'old' ],
        [ 4, 'lastname', 'young' ],
        [ 4, 'lastname', 'old' ]
      ]
    
about 4 years ago · Juan Pablo Isaza Report

0

Is this what you are looking for?

function teste() {
  let array = [[3, 'name', 'old'], [4, 'lastname', 'young'], [2, 'name', 'old'], [4, 'lastname', 'old']];

  let result = Object.values(array.reduce((c, v) => {
    if (c[v[1]]) c[v[1]][0] += v[0]; else c[v[1]] = v;
    if (c[v[2]]) c[v[1]][0] += v[0]; else c[v[2]] = v;                               
    return c;
  }, {}));

  console.log(result);
}


Execution log
2:03:43 PM  Notice  Execution started
2:03:43 PM  Info    [ [ 7, 'name', 'old' ],
  [ 7, 'name', 'old' ],
  [ 12, 'lastname', 'young' ],
  [ 12, 'lastname', 'young' ] ]
2:03:44 PM  Notice  Execution completed
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!